using Intelli.Cust.Svcs.Models;
using Intelli.Cust.Svcs.Services;
using Microsoft.AspNetCore.Mvc;

namespace Intelli.Cust.Svcs.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class IntelligentCustomerServiceController : ControllerBase
    {
        private readonly IIntelligentCustomerService _customerService;
        private readonly ILogger<IntelligentCustomerServiceController> _logger;

        public IntelligentCustomerServiceController(
            IIntelligentCustomerService customerService,
            ILogger<IntelligentCustomerServiceController> logger)
        {
            _customerService = customerService;
            _logger = logger;
        }

        /// <summary>
        /// 发送消息到智能客服
        /// </summary>
        /// <param name="request">用户消息请求</param>
        /// <returns>智能客服回复</returns>
        [HttpPost("chat")]
        public async Task<ActionResult<CustomerServiceResponse>> Chat([FromBody] ChatRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.Message))
                {
                    return BadRequest("消息内容不能为空");
                }

                var response = await _customerService.ProcessUserInputAsync(
                    request.UserId, 
                    request.Message, 
                    request.SessionId);

                _logger.LogInformation("用户消息处理完成: UserId={UserId}, SessionId={SessionId}", 
                    request.UserId, request.SessionId);

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理用户消息时发生错误: UserId={UserId}, SessionId={SessionId}", 
                    request.UserId, request.SessionId);
                
                return StatusCode(500, new CustomerServiceResponse
                {
                    Content = "系统繁忙，请稍后重试",
                    Type = ResponseType.Error,
                    RequiresHumanIntervention = true,
                    ErrorMessage = "内部服务器错误"
                });
            }
        }

        /// <summary>
        /// 获取对话历史
        /// </summary>
        /// <param name="sessionId">会话ID</param>
        /// <param name="limit">限制条数</param>
        /// <returns>对话历史列表</returns>
        [HttpGet("history/{sessionId}")]
        public async Task<ActionResult<List<ConversationHistory>>> GetConversationHistory(
            string sessionId, 
            [FromQuery] int limit = 10)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(sessionId))
                {
                    return BadRequest("会话ID不能为空");
                }

                var history = await _customerService.GetConversationHistoryAsync(sessionId, limit);
                return Ok(history);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取对话历史时发生错误: SessionId={SessionId}", sessionId);
                return StatusCode(500, "获取对话历史失败");
            }
        }

        /// <summary>
        /// 评价回复质量
        /// </summary>
        /// <param name="request">评价请求</param>
        /// <returns>评价结果</returns>
        [HttpPost("rate")]
        public async Task<ActionResult> RateResponse([FromBody] RateRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.SessionId) || 
                    string.IsNullOrWhiteSpace(request.MessageId))
                {
                    return BadRequest("会话ID和消息ID不能为空");
                }

                if (request.Rating < 1 || request.Rating > 5)
                {
                    return BadRequest("评分必须在1-5之间");
                }

                await _customerService.RateResponseAsync(
                    request.SessionId, 
                    request.MessageId, 
                    request.Rating, 
                    request.Feedback);

                _logger.LogInformation("用户评价完成: SessionId={SessionId}, MessageId={MessageId}, Rating={Rating}", 
                    request.SessionId, request.MessageId, request.Rating);

                return Ok(new { message = "评价提交成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "提交评价时发生错误: SessionId={SessionId}, MessageId={MessageId}", 
                    request.SessionId, request.MessageId);
                return StatusCode(500, "评价提交失败");
            }
        }

        /// <summary>
        /// 初始化知识库
        /// </summary>
        /// <returns>初始化结果</returns>
        [HttpPost("knowledge/initialize")]
        public async Task<ActionResult> InitializeKnowledgeBase()
        {
            try
            {
                await _customerService.InitializeKnowledgeBaseAsync();
                return Ok(new { message = "知识库初始化完成" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化知识库时发生错误");
                return StatusCode(500, "知识库初始化失败");
            }
        }

        /// <summary>
        /// 添加知识库文档
        /// </summary>
        /// <param name="request">文档添加请求</param>
        /// <returns>添加结果</returns>
        [HttpPost("knowledge/document")]
        public async Task<ActionResult> AddKnowledgeDocument([FromBody] AddDocumentRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.Content))
                {
                    return BadRequest("文档内容不能为空");
                }

                await _customerService.AddKnowledgeDocumentAsync(request.Content, request.Metadata);
                return Ok(new { message = "文档添加成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加知识库文档时发生错误");
                return StatusCode(500, "文档添加失败");
            }
        }

        /// <summary>
        /// 健康检查
        /// </summary>
        /// <returns>系统状态</returns>
        [HttpGet("health")]
        public ActionResult Health()
        {
            return Ok(new 
            { 
                status = "healthy", 
                timestamp = DateTime.UtcNow,
                service = "Intelligent Customer Service",
                version = "1.0.0"
            });
        }
    }

    // 请求模型
    public class ChatRequest
    {
        public string UserId { get; set; } = string.Empty;
        public string SessionId { get; set; } = string.Empty;
        public string Message { get; set; } = string.Empty;
    }

    public class RateRequest
    {
        public string SessionId { get; set; } = string.Empty;
        public string MessageId { get; set; } = string.Empty;
        public int Rating { get; set; }
        public string? Feedback { get; set; }
    }

    public class AddDocumentRequest
    {
        public string Content { get; set; } = string.Empty;
        public Dictionary<string, object> Metadata { get; set; } = new();
    }
} 